import ctypes

class DynamicArray(object):
  def __init__(self):
    '''
    Dynamic array class
    '''
    self.count = 0
    self.capacity = 1
    self.array = self.make_array(self.capacity)
    
  def __len__(self): # For len() function
    '''
    Returns a new array with new capacity
    '''
    return self.count
    
  def __getitem__(self, idx): # For []
    '''
    Returns element at index idx
    '''
    if not 0 <= idx < self.count:
      return IndexError('Index is out of bounds')
      
    return self.array[idx]
    
  def append(self, element):
    '''
    Add element to end of the array
    '''
    if self.count == self.capacity:
      self._resize(2 * self.capacity)
    
    self.array[self.count] = element
    self.count += 1
      
  def insertAt(self, element, index):
    '''
    Insert element at specific index
    '''
    if index < 0 or index > self.count:
      return IndexError('Invalid insert position.')
      
    if self.count == self.capacity:
      self._resize(2 * self.capacity)
      
    for i in range(self.count - 1, index - 1, -1):
      self.array[i + 1] = self.array[i]
      
    self.array[index] = element
    self.count += 1
  
  def delete(self):
    '''
    Delete element from end of array
    '''
    if self.count == 0:
      return
      
    self.array[self.count - 1] = 0
    self.count -= 1
    
  def _resize(self, new_capacity):
    '''
    Resize internal array to new_capacity
    '''
    new_array = self.make_array(new_capacity)
    for i in range(self.count):
      new_array[i] = self.array[i]
    
    self.array = new_array
    self.capacity = new_capacity
    
  def make_array(self, new_capacity):
    '''
    Returns a new array with new capacity
    '''
    return (new_capacity * ctypes.py_object)()


arr = DynamicArray()
arr.append('a')
arr.insertAt('b', 1)

print(arr[0]);
print(arr[1]);

arr.delete()
print(arr[1])
  
